<template>
  <div class="goods-list">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="商品ID">
            <el-input v-model="searchForm.goods_id" placeholder="请输入商品ID"></el-input>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="searchForm.goods_name" placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item label="排序方式">
            <el-select v-model="searchForm.sort" placeholder="请选择排序方式">
              <el-option label="默认排序" value="default"></el-option>
              <el-option label="价格升序" value="price_asc"></el-option>
              <el-option label="价格降序" value="price_desc"></el-option>
              <el-option label="销量升序" value="sales_asc"></el-option>
              <el-option label="销量降序" value="sales_desc"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" @click="handleAdd">新增商品</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <el-table
        max-height="400px"
        v-loading="loading"
        :data="goodsList"
        border
        style="width: 100% ;margin-bottom: 20px;"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="table-expand">
              <el-form-item>
                <el-card class="box-card">
                  <div v-if="props.row.goods_specs">
                  最高价格 ：<span style="color: red;font-size: 16px;">{{ props.row.goods_specs.max_price }}</span>&nbsp;&nbsp;&nbsp;&nbsp;
                  最低价格 ：<span style="color: red;font-size: 16px;">{{ props.row.goods_specs.min_price }}</span>&nbsp;&nbsp;&nbsp;&nbsp;
                  规格数量 ：<span style="color: red;font-size: 16px;">{{ props.row.goods_specs.spec_count }}</span> <br>
                  规格列表 ：
                  <el-table :data="props.row.goods_specs.specs" border size="small" style="width: 100%">
                    <!-- <el-table-column prop="spec_id" label="规格ID" width="80"></el-table-column> -->
                    <el-table-column prop="spec_no" label="规格编号" width="100"></el-table-column>
                    <el-table-column prop="spec_name" label="规格名称" width="180"></el-table-column>
                    <el-table-column prop="spec_code" label="规格编码" width="180"></el-table-column>
                    <el-table-column prop="spec_unit_name" label="单位" width="80"></el-table-column>
                    <el-table-column prop="spec_aux_unit_name" label="辅助单位" width="100"></el-table-column>
                    <el-table-column prop="retail_price" label="零售价" width="100">
                      <template slot-scope="scope">
                        ¥{{ scope.row.retail_price?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="wholesale_price" label="批发价" width="100">
                      <template slot-scope="scope">
                        ¥{{ scope.row.wholesale_price?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="market_price" label="市场价" width="100">
                      <template slot-scope="scope">
                        ¥{{ scope.row.market_price?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="member_price" label="会员价" width="100">
                      <template slot-scope="scope">
                        ¥{{ scope.row.member_price?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <!-- <el-table-column prop="custom_price1" label="自定义价格1" width="100">
                      <template slot-scope="scope">
                        ¥{{ scope.row.custom_price1?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="custom_price2" label="自定义价格2" width="100">
                      <template slot-scope="scope">
                        ¥{{ scope.row.custom_price2?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="weight" label="重量(kg)" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.weight?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column> -->
                    <!-- <el-table-column prop="length" label="长(cm)" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.length?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="width" label="宽(cm)" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.width?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="height" label="高(cm)" width="100">
                      <template slot-scope="scope">
                        {{ scope.row.height?.toFixed(2) || '-' }}
                      </template>
                    </el-table-column> -->
                      <!-- <el-table-column prop="is_sn_enable" label="序列号" width="80">
                        <template slot-scope="scope">
                          <el-tag :type="scope.row.is_sn_enable === '1' ? 'success' : 'info'">
                            {{ scope.row.is_sn_enable === '1' ? '启用' : '禁用' }}
                          </el-tag>
                        </template>
                      </el-table-column> -->
                    <!-- <el-table-column prop="deleted" label="状态" width="80">
                      <template slot-scope="scope">
                        <el-tag :type="scope.row.deleted === '0' ? 'success' : 'danger'">
                          {{ scope.row.deleted === '0' ? '正常' : '已删除' }}
                        </el-tag>
                      </template>
                    </el-table-column> -->
                    <!-- <el-table-column prop="spec_created" label="创建时间" width="160"></el-table-column>
                    <el-table-column prop="spec_modified" label="修改时间" width="160"></el-table-column> -->
                    <!-- <el-table-column label="操作" width="150" fixed="right">
                      <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleEditSpec(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDeleteSpec(scope.row)">删除</el-button>
                      </template>
                    </el-table-column> -->
                  </el-table>
                </div>
                <div v-else class="no-specs">
                  暂无规格数据
                </div>
                </el-card>
           
             
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="goods_id" label="ID" width="80"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称" min-width="200"></el-table-column>
        <el-table-column prop="goods_no" label="商品编号" width="120"></el-table-column>
        <el-table-column prop="brand_name" label="品牌" width="120"></el-table-column>
        <el-table-column prop="class_name" label="分类" width="120"></el-table-column>
        <el-table-column prop="sales_quantity" label="销量" width="100"></el-table-column>
        <el-table-column prop="sales_amount" label="销售额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.sales_amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="order_count" label="订单数" width="100"></el-table-column>
        <el-table-column prop="last_sale_date" label="最后销售日期" width="180"></el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <!-- <el-button size="mini" type="primary" @click="handlePrice(scope.row)">管理</el-button> -->
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getGoodsList } from '@/api/goods'

export default {
  name: 'GoodsList',
  data() {
    return {
      // 搜索表单
      searchForm: {
        goods_id: '',
        goods_name: '',
        sort: 'default',
        priceAsc: false,
        salesAsc: false
      },
      // 表格数据
      goodsList: [],
      loading: false,
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  mounted() {
    console.log('GoodsList mounted')
  },
  created() {
    console.log('GoodsList created')
    this.fetchData()
  },
  methods: {
    // 获取商品列表
    async fetchData() {
      try {
        this.loading = true
        console.log('Fetching goods list with params:', {
          page: this.currentPage,
          page_size: this.pageSize,
          ...this.searchForm
        })

        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          goods_id: this.searchForm.goods_id,
          goods_name: this.searchForm.goods_name,
          sort: this.searchForm.sort,
          price_asc: this.searchForm.priceAsc,
          sales_asc: this.searchForm.salesAsc
        }

        const res = await getGoodsList(params)
        console.log('Goods list response:', res)

        if (res && res.data) {
          this.goodsList = res.data.items || []
          this.total = res.data.total || 0
        } else {
          console.warn('Invalid response format:', res)
          this.$message.warning('获取数据格式不正确')
          this.goodsList = []
          this.total = 0
        }
      } catch (error) {
        console.error('Error fetching goods list:', error)
        // 添加更详细的错误信息
        const errorMessage = error.response?.data?.message || error.message || '获取商品列表失败'
        console.error('Error details:', {
          message: errorMessage,
          status: error.response?.status,
          data: error.response?.data,
          config: error.config
        })
        this.$message.error(errorMessage)
        this.goodsList = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 处理搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        goods_id: '',
        goods_name: '',
        sort: 'default',
        priceAsc: false,
        salesAsc: false
      }
      this.handleSearch()
    },

    // 处理分页变化
    handlePageChange(page) {
      this.currentPage = page
      this.fetchData()
    },

    // 处理每页条数变化
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchData()
    },

    // 处理编辑
    handleEdit(row) {
      console.log('Edit goods:', row)
      this.$router.push(`/products/edit/${row.goods_id}`)
    },

    // 处理价格管理
    handlePrice(row) {
      console.log('Manage price for goods:', row)
      this.$router.push({
        name: 'GoodsPrice',
        query: {
          goods_id: row.goods_id,
          goods_name: row.goods_name,
          goods_no: row.goods_no,
          brand_id: row.brand_id,
          brand_name: row.brand_name,
          class_id: row.class_id,
          class_name: row.class_name,
          order_id: row.order_id || '',
          order_status: row.order_status || '',
          payment_status: row.payment_status || '',
          payment_method: row.payment_method || '',
          trade_no: row.trade_no || '',
          goods_total: row.goods_total || 0,
          total_price: row.total_price || 0,
          delivery_fee: row.delivery_fee || 0,
          create_time: row.create_time || ''
        }
      })
    },

    // 查看商品详情
    handleViewDetails(row) {
      console.log('查看商品详情:', row)
      // TODO: 实现查看详情功能
    },

    handleDelete(row) {
      this.$confirm('确认删除该商品?', '提示', {
        type: 'warning'
      }).then(() => {
        // TODO: 实现删除逻辑
        console.log('删除商品：', row)
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    handleEditSpec(row) {
      console.log('编辑商品规格:', row)
      // TODO: 实现编辑规格功能
    },
    handleDeleteSpec(row) {
      this.$confirm('确认删除该商品规格?', '提示', {
        type: 'warning'
      }).then(() => {
        // TODO: 实现删除规格逻辑
        console.log('删除商品规格：', row)
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    // 处理新增
    handleAdd() {
      this.$router.push('/goods/edit')
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-list {
  .search-bar {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .table-expand {
    padding: 20px;
    
    .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 100%;
    }

    .el-table {
      margin-top: 10px;
      
      // 添加横向滚动条
      .el-table__body-wrapper {
        overflow-x: auto;
      }
    }
  }
  
  .no-specs {
    color: #909399;
    font-size: 14px;
    padding: 10px 0;
  }
}
</style> 